package com.antdesignbackend.backend.news.news.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.news.newsusers.entity.NewsUsers;
import com.antdesignbackend.backend.news.newsusers.entity.entityVo.NewsUsersVo;
import com.antdesignbackend.backend.news.newsusers.service.NewsUsersService;
import com.antdesignbackend.backend.news.notice.entity.entityVo.NoticeVo;
import com.antdesignbackend.backend.service.UserService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.news.news.entity.News;
import com.antdesignbackend.backend.news.news.entity.entityVo.NewsVo;
import com.antdesignbackend.backend.news.news.service.NewsService;

/**
 * 消息推送
 *
 * @author 不二
 * @email news
 * @date 2020-07-27 16:51:20
 */

@Controller
@RequestMapping("/news")
@Slf4j
public class NewsController extends BaseController{

	private static final String FUN_NAME = "消息推送";//功能名称
	private Integer nid;

	@Autowired
	private NewsService newsService;

	@Autowired
	private UserService userService;
	@Autowired
	private NewsUsersService newsUsersService;

	@GetMapping("/index")
	@AuthToken
	public String index() {
		return "news/news/index";
	}

	@GetMapping("/push/{id}")
	@AuthToken
	public String push(@PathVariable("id") Integer id) {
		this.nid = id;
		return "news/news/push";
	}

	@GetMapping("/mobile/{id}")
	@AuthToken
	public String mobile(@PathVariable("id") Integer id, Model model) {
		NewsUsers newsUsers = newsUsersService.getById(id);
		if (newsUsers == null){
			return "404";
		}
		if (newsUsers.getStatus() == 0){
			newsUsers.setStatus(1);
			newsUsersService.updateById(newsUsers);
		}
		//根据消息id查询消息
		News news = newsService.getById(newsUsers.getNid());
		if (news == null){
			return "404";
		}
		model.addAttribute("news",news);
		return "news/news/mobile";
	}


	@PostMapping("/tableSearch")
	@ResponseBody
	ReturnVO tableSearch(@RequestBody NewsVo newsVo) throws SecurityException, IllegalArgumentException{
		ReturnVO result = new ReturnVO();
		List<NewsVo> list = new ArrayList<>();
		QueryWrapper<NewsVo> wrapper = new QueryWrapper<>();
		//判断用户权限
		Users users = userService.getById(getLoginUserId());
		if (users.getAuthType() == 1){ //地市权限
			wrapper.eq("authCity",users.getAuthCity());
		}else if (users.getAuthType() == 2){ //区县权限
			wrapper.eq("authDistrict",users.getAuthDistrict());
		}else if (users.getAuthType() == 3){
			wrapper.eq("authTown",users.getAuthTown());
		}else {
			return result;
		}
		if(newsVo.getAuthCity() != null && newsVo.getAuthCity() != -1){
			wrapper.eq("authCity",newsVo.getAuthCity());
		}
		if(newsVo.getAuthDistrict() != null && newsVo.getAuthDistrict() != -1){
			wrapper.eq("authDistrict",newsVo.getAuthDistrict());
		}
		if(newsVo.getAuthTown() != null && newsVo.getAuthTown() != -1){
			wrapper.eq("authTown",newsVo.getAuthTown());
		}
		if (newsVo.getTitle() != null && !newsVo.getTitle().equals("")){
			wrapper.like("title",newsVo.getTitle());
		}
		wrapper.orderByDesc("CreateTime");
		int total = newsService.count(wrapper);
		if (total > 0){
			list = newsService.search(wrapper,new Page<NewsVo>(newsVo.getPageIndex(),newsVo.getPageSize()));
			if (list.size() > 0){
				for (NewsVo newsVo1:list){
					StringBuilder rolesName = new StringBuilder();
					if (newsVo1.getRoles() != null && !newsVo1.getRoles().equals("")){
						String[] strings = newsVo1.getRoles().split(",");
						for (String s:strings){
							if ("2".equals(s)){
								rolesName.append("执法管理人员,");
							}else if ("6".equals(s)){
								rolesName.append("检疫人员,");
							}else if ("3".equals(s)){
								rolesName.append("养殖企业,");
							}else if ("4".equals(s)){
								rolesName.append("屠宰企业,");
							}else if ("5".equals(s)){
								rolesName.append("无害化处理企业,");
							}
						}
					}
					String rolesName1 = "";
					if (rolesName.length() > 0){
						rolesName1 =  rolesName.substring(0,rolesName.length() - 1);
					}
					newsVo1.setRolesName(rolesName1);
					//去掉内容html标签，用于显示
					if (newsVo1.getContent() != null){
						String showContent = newsVo1.getContent().replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
						if (showContent.length() > 7){
							showContent = showContent.substring(0,7) + "...";
						}
						newsVo1.setShowContent(showContent);
					}
				}
			}
		}
		result.setTotal(total);
		result.setData(list);
		return result;
	}

	@GetMapping("/getById/{id}")
	@ResponseBody
	public	News getById(@PathVariable(name = "id") String id) {
		News obj = newsService.getById(id);
		return obj;
	}

	@PostMapping("/save")
	@ResponseBody
	public ReturnVO save(@RequestBody News news){
		ReturnVO result = new ReturnVO();
		news.setCreateUid(getLoginUserId());
		news.setCreateTime(new Date());
		try {
			newsService.createNews(news);
		}catch (Exception e){
			log.error(e.getMessage());
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	@PostMapping("update")
	@ResponseBody
	public ReturnVO updateById(@RequestBody News news){
		ReturnVO result = new ReturnVO();
		news.setCreateUid(getLoginUserId());
		news.setCreateTime(new Date());
		try {
			newsService.updateNews(news);
		}catch (Exception e){
			log.error(e.getMessage());
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	/**
     * 根据id删除
     */
	@DeleteMapping("/deleteById/{id}")
	@ResponseBody
	public ReturnVO deleteById(@PathVariable Serializable id) {
		ReturnVO result = new ReturnVO();
		if (newsService.removeById(Integer.parseInt(id.toString())) == true) {
			result.setMessage("删除成功");
		} else {
			result.setMessage("删除失败");
			result.setCode("0");
		}
		return result;
	}

	@PostMapping("/tableSearchPush")
	@ResponseBody
	ReturnVO tableSearchPush(@RequestBody NewsUsersVo newsUsersVo) throws SecurityException, IllegalArgumentException{
		ReturnVO result = new ReturnVO();
		List<NewsUsersVo> list = new ArrayList<>();
		QueryWrapper<NewsUsersVo> wrapper = new QueryWrapper<>();
		if (newsUsersVo.getStatus() != null && newsUsersVo.getStatus() != -1){
			wrapper.eq("status",newsUsersVo.getStatus());
		}
		if (newsUsersVo.getUserName() != null && !newsUsersVo.getUserName().equals("")){
			wrapper.eq("UserName",newsUsersVo.getUserName());
		}
		if (newsUsersVo.getPhone() != null && !newsUsersVo.getPhone().equals("")){
			wrapper.eq("Phone",newsUsersVo.getPhone());
		}
		if (newsUsersVo.getEnterpriseName() != null && !newsUsersVo.getEnterpriseName().equals("")){
			wrapper.eq("EnterpriseName",newsUsersVo.getEnterpriseName());
		}
		wrapper.eq("nid",nid);
		wrapper.orderByDesc("CreateTime");
		int total = newsUsersService.count(wrapper);
		if (total > 0){
			list = newsUsersService.search(wrapper,new Page<NewsUsersVo>(newsUsersVo.getPageIndex(),newsUsersVo.getPageSize()));
			if (list.size() > 0){
				for (NewsUsersVo newsUsersVo1:list){
					//去掉内容html标签，用于显示
					if (newsUsersVo1.getContent() != null){
						String showContent = newsUsersVo1.getContent().replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
						if (showContent.length() > 16){
							showContent = showContent.substring(0,16) + "...";
						}
						newsUsersVo1.setContent(showContent);
					}
				}
			}
		}
		result.setTotal(total);
		result.setData(list);
		return result;

	}

}
